#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2022/6/13 14:28
# @Author : Violet
# @File : user.py
# @desc : 用户增删改查封装

from sqlalchemy import select, insert, delete, update
from models.user import User, Role, UserRole, RoleAccess, Access
from schemas.user import CreateUser


# ---------------------------------------------美观线-------------------------------------------------------


async def get_user_for_username(db_session, username: str, ):
    """
    查询一个管理员
    :param username:
    :return:
    """
    async with db_session.begin():
        result = await db_session.execute(select(User).where(User.username == username))
        # 第一条数据
        await db_session.close()  # 释放会话
    return result.scalar()

async def get_user_for_id(db_session, user_id: int):
    """
    查询一个管理员
    :param username:
    :return:
    """
    async with db_session.begin():
        result = await db_session.execute(select(User).where(User.id == user_id))
        # 第一条数据
        await db_session.close()  # 释放会话
    return result.scalar()



async def add_user(db_session, data: CreateUser):
    """
    添加管理员
    :param data:
    :return:
    """
    async with db_session.begin():
        data = await db_session.execute(insert(User).values(data.dict()))
        return data.rowcount

async def get_users(db_session):
    """
    查询管理员
    :param db_session:
    :return:
    """

    async with db_session.begin():
        result = await db_session.execute(select(User))
        await db_session.close()  # 释放会话
    return [content.to_dict() for content in result.scalars()]

async def delete_user(user_id :int ,db_session):
    """
    查询管理员
    :param db_session:
    :return:
    """
    async with db_session.begin():
        result = await db_session.execute(delete(User).where(User.id == user_id))
    return result.rowcount


async def update_user(user_id :int ,data:dict,db_session):
    """
    查询管理员
    :param db_session:
    :return:
    """
    async with db_session.begin():
        result = await db_session.execute(update(User).where(User.id==user_id).values(data))
    return result.rowcount
